package com.qst.itoffer.util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBUtils {

    static String user = "nchk";
    static String USER_PWD = "123456";
    static String url = "jdbc:mysql://106.225.197.1:3306/itoffer?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, user, USER_PWD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 执行查询，返回结果集列表
     * @param sql SQL查询语句
     * @param params 查询参数
     * @return List<Map<String, Object>> 每行数据为一个Map，键为列名，值为数据
     */
    public static List<Map<String, Object>> executeQuery(String sql, Object... params) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);

            // 设置参数
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }

            rs = pstmt.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            while (rs.next()) {
                Map<String, Object> rowData = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    rowData.put(metaData.getColumnName(i), rs.getObject(i));
                }
                resultList.add(rowData);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeJDBC(rs, pstmt, conn);
        }

        return resultList;
    }

    /**
     * 执行更新操作（INSERT、UPDATE、DELETE）
     * @param sql SQL语句
     * @param params 参数列表
     * @return 受影响的行数
     */
    public static int executeUpdate(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int affectedRows = 0;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);

            // 设置参数
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }

            affectedRows = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeJDBC(null, pstmt, conn);
        }

        return affectedRows;
    }

    /**
     * 执行插入操作并返回自增主键
     * @param sql SQL插入语句
     * @param params 参数列表
     * @return 自增主键值
     */
    public static long executeInsertAndGetKey(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        long generatedKey = -1;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

            // 设置参数
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }

            pstmt.executeUpdate();

            // 获取自增主键
            ResultSet rs = pstmt.getGeneratedKeys();
            if (rs.next()) {
                generatedKey = rs.getLong(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeJDBC(null, pstmt, conn);
        }

        return generatedKey;
    }

    /**
     * 执行批量操作
     * @param sql SQL语句
     * @param paramsList 参数列表，每个元素是一组参数
     * @return 每条语句影响的行数数组
     */
    public static int[] executeBatch(String sql, List<Object[]> paramsList) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int[] result = null;

        try {
            conn = getConnection();
            pstmt = conn.prepareStatement(sql);

            // 添加批量参数
            for (Object[] params : paramsList) {
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
                pstmt.addBatch();
            }

            result = pstmt.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeJDBC(null, pstmt, conn);
        }

        return result;
    }

    /**
     * 关闭JDBC资源
     */
    public static void closeJDBC(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        //查询
        List<Map<String, Object>> users = DBUtils.executeQuery(
                "SELECT * FROM tb_users WHERE user_id = ?",
                1
        );
        for (Map<String, Object> user : users) {
            System.out.println("ID: " + user.get("USER_ID") + ", Name: " + user.get("USER_LOGNAME"));
        }

//        //插入
//        // 插入并获取自增ID
//        long newUserId = DBUtils.executeInsertAndGetKey(
//                "INSERT INTO tb_users(USER_LOGNAME, USER_PWD) VALUES(?, ?)",
//                "newuser", "123456"
//        );
//        System.out.println("插入成功，ID: " + newUserId);
//
//        //更新
//        int affectedRows = DBUtils.executeUpdate(
//                "UPDATE tb_users SET USER_LOGNAME = ? WHERE id = ?",
//                "updatedname", 1
//        );
//        System.out.println("更新了 " + affectedRows + " 行数据");
//
//        //批量操作
//        List<Object[]> batchParams = new ArrayList<>();
//        batchParams.add(new Object[]{"user1", "pass1"});
//        batchParams.add(new Object[]{"user2", "pass2"});
//        batchParams.add(new Object[]{"user3", "pass3"});
//
//        int[] results = DBUtils.executeBatch(
//                "INSERT INTO tb_users(USER_LOGNAME, USER_PWD) VALUES(?, ?)",
//                batchParams
//        );
//        System.out.println("批量插入了 " + results.length + " 条数据");
    }
}
